package com.zhouchao.rpc.consumer.component;

import com.zhouchao.register.zookeeper.ZookeeperRegisterManager;
import com.zhouchao.rpc.common.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author: zhouchao
 * @Date: 2021/08/15 22:17
 * @Description:
 */
@Slf4j
@Component
public class ReportHandler {
    private static final ZookeeperRegisterManager REGISTER_MANAGER = new ZookeeperRegisterManager();

    ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);

    @PostConstruct
    public void init() {
        scheduled.scheduleAtFixedRate(() -> {
            try {
                reportServer();
            } catch (Exception e) {
                log.error("定时任务异常", e);
            }
        }, 0, 5, TimeUnit.SECONDS);
    }


    public void reportServer() {
        log.info("开始上报服务");
        long currentTime = System.currentTimeMillis();
        Map<String, Server> serverMap = ZookeeperRegisterManager.SERVER_MAP;
        if (serverMap.isEmpty()) {
            log.info("没有服务要上报");
            return;
        }
        for (Map.Entry<String, Server> entry : ZookeeperRegisterManager.SERVER_MAP.entrySet()) {
            Server server = entry.getValue();
            if (currentTime - server.getReportTime() > 5000) {
                // 超过5秒清空内容
                log.info("服务超过了5秒，清空数据：{}", server);
                server.setCastTime(0);
                server.setReportTime(0);
            } else {
                // 5秒以内更新zookeeper的值
                log.info("更新服务数据：{}", server);
            }
            REGISTER_MANAGER.reportServer(server);
        }
    }
}
